import os
from pathlib import Path
from queue import Queue
import threading
from tkinter import filedialog
from typing import Any, Union
from .view import *
from fstatistics import *

class SdtBox(Tk):
    def set_cols(self,cols:Iterable[str]):
        self.tree["columns"] = cols
        for col in cols:
            self.tree.column(col, minwidth=80, stretch=YES)
            self.tree.heading(col, text=col)
    
    def clear(self):
        for item in self.tree.get_children():
            self.tree.delete(item)
    
    def set_data(self,data:Iterable[Iterable[Any]]):
        for item in data:
            to_add = list(map(str,item))
            self.tree.insert("", "end", values=to_add)
    
    def __init__(self,sdtfile:str):
        super().__init__()
        self.__file:str = sdtfile
        
        self.title("SDT文件查看器")
        self.geometry("640x400")
        self.tree = Treeview(self) 
        self.tree['show'] = 'headings'
        self.tree.grid(row=0,column=0,sticky='nsew')
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.VScroll1 = Scrollbar(self, orient='vertical', command=self.tree.yview)
        self.VScroll1.grid(row=0, column=1, sticky='ns')
        self.HScroll1 = Scrollbar(self, orient='horizontal', command=self.tree.xview)
        self.HScroll1.grid(row=1, column=0, sticky='ew')
        self.tree.configure(yscrollcommand=self.VScroll1.set,xscrollcommand=self.HScroll1.set)
        
        self._Q = Queue()
        
        threading.Thread(target=self.load,args=(self.__file,)).start()
        self.after(100,self._upd)

    def _upd(self):
        cnt = 0
        while not self._Q.empty() and cnt<50:
            op,val = self._Q.get()
            cnt += 1
            if op=='L':
                self.__tb:ReadOnlyTable = val
                self.set_cols(self.__tb.head)
                self.clear()
                self.set_data(self.__tb.data)
        self.after(100,self._upd)
    
    @staticmethod
    def __digits(s:str)->Union[None,int,float]:
        '''从字符串中提取数字'''
        ret = ""
        has_dot = False
        for c in s:
            if c.isdigit() or c == '.':
                if c == '.':
                    if has_dot: break
                    has_dot = True
                ret += c
        if ret == "": return None
        return float(ret) if has_dot else int(ret)
            
    def load(self,filename:str):
        while not Path(filename).exists():
            filename = filedialog.askopenfilename(title="请选择SDT文件",filetypes=[("SDT文件",".sdt"),("压缩的SDT文件",".sdt.gz")],initialdir=os.getcwd())
            if filename == "": os._exit(-1)
        self._Q.put_nowait(('L', ReadOnlyTable(filename,preload=True)))
